package org.example.scoresystem_backen.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;
import org.springframework.stereotype.Component;

import java.util.Date;

/**
 * 简化的JWT工具类
 */
@Component
public class JwtUtil {

    // 简化配置，直接硬编码
    private static final String SECRET = "scoresystem-secret-key";
    private static final long EXPIRATION = 24 * 60 * 60 * 1000; // 24小时

    /**
     * 生成JWT令牌
     */
    public String generateToken(Integer userId, String username, String userType) {
        Date now = new Date();
        Date expiration = new Date(now.getTime() + EXPIRATION);

        return JWT.create()
                .withSubject(username)
                .withClaim("userId", userId)
                .withClaim("userType", userType)
                .withIssuedAt(now)
                .withExpiresAt(expiration)
                .sign(Algorithm.HMAC256(SECRET));
    }

    /**
     * 验证令牌
     */
    public boolean validateToken(String token) {
        try {
            JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
            return true;
        } catch (JWTVerificationException e) {
            return false;
        }
    }

    /**
     * 从令牌中获取用户ID
     */
    public Integer getUserIdFromToken(String token) {
        DecodedJWT jwt = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return jwt.getClaim("userId").asInt();
    }

    /**
     * 从令牌中获取用户名
     */
    public String getUsernameFromToken(String token) {
        DecodedJWT jwt = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return jwt.getSubject();
    }

    /**
     * 从令牌中获取用户类型
     */
    public String getUserTypeFromToken(String token) {
        DecodedJWT jwt = JWT.require(Algorithm.HMAC256(SECRET)).build().verify(token);
        return jwt.getClaim("userType").asString();
    }
}
